package com.blb.thread;

/**
 *  A线程循环输出A，B线程循环输出B，要求两个线程交替输出ABABAB.....
 */
public class ThreadPrintDemo {

    public static void main(String[] args) {
        new Thread(() -> {
            synchronized (ThreadPrintDemo.class) {
                for (int i = 0; i < 10; i++) {
                    System.out.println("A");
                    try {
                        //通知对方线程执行
                        ThreadPrintDemo.class.notify();
                        //当前线程等待
                        ThreadPrintDemo.class.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        new Thread(() -> {
            synchronized (ThreadPrintDemo.class) {
                for (int i = 0; i < 10; i++) {
                    System.out.println("B");
                    try {
                        //通知对方线程执行
                        ThreadPrintDemo.class.notify();
                        //当前线程等待
                        ThreadPrintDemo.class.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        try {
            Thread.sleep(500);
            synchronized (ThreadPrintDemo.class){
                ThreadPrintDemo.class.notifyAll();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
